package com.qipay.security.sign.filter;

import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.jwt.JWTUser;
import com.qipay.security.sign.service.SignService;
import com.qipay.utils.RequestUtils;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class SignTokenFilter extends OncePerRequestFilter {

    @Autowired
    SignService signService;

    @Value("${api.response.sign.name}")
    private String sigKey;

    private List<String> urls = new ArrayList<>();

    public SignTokenFilter(String... url) {
        Collections.addAll(urls, url.clone());
    }

    private JWTUser getLoginUser(HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            JWTUser userImpl =
                    (JWTUser) authentication.getPrincipal();
            return userImpl;
        }
        return null;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        JWTUser user = getLoginUser(httpServletRequest);
        if (user == null) {
            httpServletResponse.setStatus(HttpStatus.SC_OK);
            Map<String, Object> result = ResultUtils.createStatusResult(ApiStatusEnum.UNAUTHENTICATION.getInfo()
                    , "未登录，请先登录再进行sign验证");
            httpServletResponse.setContentType("application/xml;charset=UTF-8");
            httpServletResponse.getWriter().append(XmlUtils.toString(result, "xml"));
            return;
        }

        try {
            String xml = RequestUtils.getRequestBody(httpServletRequest);
            logger.info("request from " + httpServletRequest.getRequestURI() + ", request body:" + xml);
            Map<String, Object> params = XmlUtils.toMap(xml);
            String fromSig = params.get(sigKey).toString();
            String mySig = signService.getSign(params, user.getSecret(), sigKey);
            if (!StringUtils.equals(fromSig, mySig)) {
                logger.warn("签名不一致:fromSig:" + fromSig + ", mysig:" + mySig);
                httpServletResponse.setStatus(HttpStatus.SC_OK);
                Map<String, Object> result = ResultUtils.createStatusResult(ApiStatusEnum.SIGN_ERR.getInfo()
                        , "签名错误");
                httpServletResponse.setContentType("application/xml;charset=UTF-8");
                httpServletResponse.getWriter().append(XmlUtils.toString(result, "xml"));

                return;
            }
            httpServletRequest.setAttribute("params", params);
        } catch (Exception e) {

            httpServletResponse.setStatus(HttpStatus.SC_OK);
            Map<String, Object> result = ResultUtils.createStatusResult(ApiStatusEnum.ARGUMENT_ERR.getInfo()
                    , "参数错误");
            httpServletResponse.setContentType("application/xml;charset=UTF-8");
            httpServletResponse.getWriter().append(XmlUtils.toString(result, "xml"));
            return;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private boolean isFilterUrl(HttpServletRequest request) {
        String ctxPath = request.getServletPath();
        return urls.stream().anyMatch(p -> {
            return ctxPath.startsWith(p);
        });
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return !isFilterUrl(request);
    }
}
